//
//  MainQRViewController.swift
//  JGT
//
//  Created by weihui on 2018/11/20.
//  Copyright © 2018 test. All rights reserved.
//

import UIKit
import swiftScan
import AVFoundation
//protocol QRCodeScan: QRDecodeProtocol {
//    /// 处理QR信息
//    func handleQRInfo(in qrImage: UIImage)
//}
//
//extension QRCodeScan where Self: UIViewController {
//
//    func handleQRInfo(in qrImage: UIImage) {
//        let arrayResult = LBXScanWrapper.recognizeQRImage(image: qrImage)
//
//        if arrayResult.count > 0 {
//            for result: LBXScanResult in arrayResult {
//                if let str = result.strScanned {
//                    // 协议不为空
////                    if let urlStr = str.removingPercentEncoding, let url = URL(string: urlStr), url.scheme != nil {
////                        self.transitionToWeb(withUrl: JGTURI.h5.configURI(url: urlStr))
////                        return
////                    }
////                    self.decodeMessage(message: str) { model in
////                        guard let m = model, !m.isExpired else {
////                            AlertNormalView.show(in: self, with: "无效二维码", complish: nil)
////                            return
////                        }
////                        if m.address == "" {
////                            AlertNormalView.show(in: self, with: "验证通过", complish: nil)
////                        } else {
////                            self.transitionToWeb(withUrl: m.url)
////                        }
////                    }
////                }
//            }
//        } else {
////             AlertNormalView.show(in: self, with: "未发现二维码", complish: nil)
//        }
//    }
//}
//
/// 扫一扫 扫码页面
class MainQRViewController: LBXScanViewController {
    
    // 自定义后退
    @IBOutlet weak var backButton: UIButton!
    @IBAction func backClick(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    // 无法识别
    @IBOutlet weak var detailButton: UIButton!    
    @IBAction func detailClick(_ sender: UIButton) {
//        self.transitionToWeb(withUrl: JGTURI.web.configURI(url: "/content-system/?/scanning_failed"))
    }
    
    // 开关闪光灯 照明
    @IBOutlet weak var lightButton: UIButton!
    @IBAction func lightClick(_ sender: UIButton) {
        scanObj?.changeTorch()
    }
    
    // 提示二维码位置
    @IBOutlet weak var noticeLabel: UILabel!
    @IBOutlet weak var noticePosition: NSLayoutConstraint!
    
    // 默认导航栏返回键 名字写错了
    @IBAction func searchClick(_ sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
    // 相册选择
    @IBOutlet weak var photoLibraryButton: UIButton! {
        didSet {
            photoLibraryButton.layer.cornerRadius = 16
            photoLibraryButton.layer.borderWidth = 0.5
            photoLibraryButton.layer.borderColor = UIColor.white.cgColor
        }
    }
    
    @IBAction func openPhotoLibrary(_ sender: UIButton) {
//        PhotoDelegate.share.getImage(target: self, sourceType: .photoLibrary, handle: { (image) in
//            guard let i = image else {
//                AlertNormalView.show(in: self, with: "访问失败，请在设置中修改权限！", complish: nil)
//                return
//            }
//            let arrayResult = LBXScanWrapper.recognizeQRImage(image: i)
//            if arrayResult.count > 0 {
//                self.handleCodeResult(arrayResult: arrayResult)
//                return
//            }else{
//                 AlertNormalView.show(in: self, with: "未发现二维码", complish: nil)
//            }
//        })
    }
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置扫码区域参数
        var style = LBXScanViewStyle()
        style.photoframeLineW = 2
        style.photoframeAngleW = 18
        style.photoframeAngleH = 18
        style.isNeedShowRetangle = false
        style.anmiationStyle = LBXScanViewAnimationStyle.LineMove
        style.animationImage = UIImage(named: "qrcode_Scan_weixin_Line")
        
        self.scanStyle = style
        //框向上移动10个像素
        scanStyle?.centerUpOffset += 10
        scanStyle?.photoframeAngleStyle = .Inner
        scanStyle?.colorAngle = .blue
        
        //计算消息label位置
        let defaultSpace = scanStyle?.xScanRetangleOffset ?? 0
        self.noticePosition.constant = (UIScreen.main.bounds.width - defaultSpace * 2) / 2 + 16
        
        
        addZoomGesture()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.view.bringSubviewToFront(self.noticeLabel)
        self.view.bringSubviewToFront(self.photoLibraryButton)
        self.view.bringSubviewToFront(self.lightButton)
        self.view.bringSubviewToFront(self.backButton)
        self.view.bringSubviewToFront(self.detailButton)
        
//        if let qr = self.qRScanView {
//            self.view.sendSubviewToBack(qr)
//        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    // 处理扫描规则
    override func handleCodeResult(arrayResult: [LBXScanResult]) {
        
        for result: LBXScanResult in arrayResult {
            if let str = result.strScanned {
                // 协议不为空
//                if let urlStr = str.removingPercentEncoding, let url = URL(string: urlStr), url.scheme != nil {
//                    self.transitionToWeb(withUrl: JGTURI.h5.configURI(url: urlStr))
//                    return
//                }
//                self.decodeMessage(message: str) { model in
//                    guard let m = model, !m.isExpired else {
//                        AlertNormalView.show(in: self, with: "无效二维码") {
//                            self.restart()
//                        }
//                        return
//                    }
//                    if m.address == "" {
//                        AlertNormalView.show(in: self, with: "验证通过") {
//                            self.restart()
//                        }
//                    } else {
//                        self.transitionToWeb(withUrl: m.url)
//                    }
//                }
            } else {
                restart()
            }
        }
        
    }
    
    //重新扫描
    func restart() {
        self.drawScanView()
        self.perform(#selector(LBXScanViewController.startScan), with: nil, afterDelay: 0.3)
    }
    
    // MARK: - 变焦参数
    /// 当前变焦
    private var currentZoomFactor: CGFloat = 1.0
    
}


// MARK: - 相机变焦
extension MainQRViewController: UIGestureRecognizerDelegate {
    
    /// 最小缩放
    private var minZoomFactor: CGFloat {
        if #available(iOS 11.0, *) {
            return captureDevice.minAvailableVideoZoomFactor
        }
        return 1.0
    }
    
    /// 最大缩放
    private var maxZoomFactor: CGFloat {
    
        var mzf: CGFloat!
        
        if #available(iOS 11.0, *) {
            mzf = captureDevice.maxAvailableVideoZoomFactor
        } else {
            mzf = captureDevice.activeFormat.videoMaxZoomFactor
        }
        
        return mzf
    }
    
    /// 捕获二维码设备
    private var captureDevice: AVCaptureDevice {
        AVCaptureDevice.default(for: .video)!
    }
    
    /// 添加缩放动作
    private func addZoomGesture() {
        let pinGes = UIPinchGestureRecognizer(target: self, action: #selector(zoomAction(_:)))
        pinGes.delegate = self
        view.addGestureRecognizer(pinGes)
    }
    
    /// 缩放动作
    @objc private func zoomAction(_ sender: UIPinchGestureRecognizer) {
        
        let czf = currentZoomFactor * sender.scale

        if czf > minZoomFactor && czf <= maxZoomFactor {
            do {
                switch sender.state {
                case .began, .changed:
                    try captureDevice.lockForConfiguration()
                    captureDevice.videoZoomFactor = czf
                default:
                    captureDevice.unlockForConfiguration()
                }
            } catch {
//                debugLog(error)
            }
        }
        
    }
    
    // MARK: - 代理方法
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer is UIPinchGestureRecognizer {
            currentZoomFactor = captureDevice.videoZoomFactor
        }
        return true
    }
}
